<?php


class User_Data_Mapper
{
    
private $result = null;
private $errors = null;
    
     public function fetchUserInfo($userId)
    {
        $db = Db_Helper::getInstance();
        $sql = "
                SELECT id, login, firstName, secondName, email , birthday ,phone , gender , picture, timeCreated
                FROM users 
                WHERE id='$userId'
                ";
        $row = $db->select($sql) ;  // чтобы не было 2 запроса                
        if(!$row) {
            $this->errors = NO_USER_ERROR;
            return false; 
        } else {
           $model = new User_Model($row);
           return $model; 
        }
    }    
    
      
    public function fetchAll($model, $page = 1, $limit = 10)
    {   
       // заполнение пременной поиска 
       $where = '';
       if(null != $model->getGender()){
           $where.= " AND gender = " . $model->getGender();
       }
       if(null != $model->getAgeFrom()){
           $dateFrom = Validator::getInstance()->validateYear($model->getAgeFrom());
           $where.= " AND birthday <= '" . $dateFrom . "'";
       }
       if(null != $model->getAgeTo()){
           $dateTo = Validator::getInstance()->validateYear($model->getAgeTo(),-1);
           $where.= " AND birthday >= '" . $dateTo . "'";
       } 
       if(null != $model->getName()){
           $where.= " AND firstName LIKE '%" . $model->getName() . "%'";
       }
       $db = Db_Helper::getInstance();
       $sql = "   
                    SELECT id , firstName, secondName, picture, birthday, timeCreated 
                    FROM users
                    WHERE id>0 " . $where . "
                    ORDER BY id DESC
                    LIMIT " . --$page * $limit . " , " . $limit . "
                    ";
       $arrayMessageModels = $db->selectAll($sql, 'User_Model');
       if(!$arrayMessageModels){
           $this->errors = SEARCH_USERS_ERROR ;
           return false;
       }  else {
            return $arrayMessageModels;
       } 
    }
    
    public function fetchRandom10()
    {
        $db = Db_Helper::getInstance();
        $sql = "
                SELECT id, picture
                FROM users 
                ORDER BY RAND()
                LIMIT 10
                ";
        $arrayModels = $db->selectAll($sql,'User_Model') ;  // чтобы не было 2 запроса                
        if(!$arrayModels) {
            $this->errors = NO_USER_ERROR;
            return false; 
        } else {
           return $arrayModels;
        }  
    }
    
    public function enterUser(User_Model $model)
    {
        $db = Db_Helper::getInstance();
        $sql = "
                SELECT id, login, rights 
                FROM users 
                WHERE login='" . $model->getLogin() . "' && password='" . $model->getPassword() . "'
                ";
        $row = $db->select($sql);
        if (!$row) {
            $this->errors = LOGIN_ERROR;
            return false;
        } else {
            return new User_Model($row); // здесь модель возвращается
        }
    }
 
 
 
    public function addUser( User_Model $model)
    {
        $db = Db_Helper::getInstance();
        $sql1 = "
                SELECT login 
                FROM users 
                WHERE login='" .  $model->getLogin() . "'
                LIMIT 1
                ";
        $login = $db->select($sql1);
        if (!$login) {                             // означает что такого имени нет, т.е. хорошо
            $sql2 = "
            INSERT INTO users (login,firstname,secondname,email,password,birthday,phone,picture,gender,timeCreated) 
            VALUES(
                    '" . $model->getLogin()  . "',
                    '" . $model->getFirstName()  . "',
                    '" . $model->getSecondName()  . "',
                    '" . $model->getEmail()  . "',
                    '" . $model->getPassword()  . "',
                    '" . $model->getBirthday()  . "',
                    '" . $model->getPhone()  . "',
                    '" . $model->getPicture()  . "',
                    '" . $model->getGender()  . "',
                    '" . $model->getTimeCreated()  . "'
                    )";            
            if(!$db->insert($sql2)) {
                $this->errors = QUERY_ERROR;
                return false;
            } else {
                    //сделать авторизацию
                   return $this->enterUser($model);  
            } 
        }  else {
            $this->errors = REPEAT_USER_ERROR;
            return false;
        }     
    }
    
    public function countAllUsers( Search_Model $model)
    {
        // заполнение пременной поиска 
       $where = '';
       if(null != $model->getGender()){
           $where.= " AND gender = " . $model->getGender();
       }
       if(null != $model->getAgeFrom()){
           $dateFrom = Validator::getInstance()->validateYear($model->getAgeFrom());
           $where.= " AND birthday <= '" . $dateFrom . "'";
       }
       if(null != $model->getAgeTo()){
           $dateTo = Validator::getInstance()->validateYear($model->getAgeTo(), -1);
           $where.= " AND birthday >= '" . $dateTo . "'";
       } 
       if(null != $model->getName()){
           $where.= " AND firstName LIKE '%" . $model->getName() . "%'";
       }
        $db = Db_Helper::getInstance();
        $sql = "   
                    SELECT COUNT(id)
                    FROM users
                    WHERE id>0 " . $where . "
                    ";
        $row = $db->select($sql);
        if(!$row){
            $this->errors = QUERY_ERROR;
            return false;
        } else {
            return $row['COUNT(id)'];
        }   
    }
    
    
    public function getErrors()
    {
       return $this->errors; 
    }
    
       
}
